package com.situ.music.activity;


import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.situ.music.R;
import com.situ.music.service.MusicService;

import java.util.ArrayList;

public class MusicPlayAcitvity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MusicPlayAcitvity";
    
    private static SeekBar seekBar;
    private static TextView tvProgress;
    private static TextView tvTotal;
    private ImageView ivPrevious;
    private ImageView ivPlay;
    private ImageView ivNext;

    // Service放回的控制类
    private MusicService.MusicContrll musicContrll;
    // 当前正在播放的歌曲的路径
    private String path;
    // 当前目录下面所有要播放的mp3的集合
    private ArrayList<String> mp3List;
    //当前正在播放的歌曲在mp3List集合中的下标
    private int currentMusicIndex;

    // 在Service或者线程里面，是不能直接更新主线程（UI线程）中的UI组件,
    // 需要先交给Hander，然后再更新UI
    public static Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle = msg.getData();
            int duration = bundle.getInt("duration");
            int currentPosition = bundle.getInt("currentPosition");
            seekBar.setMax(duration);
            seekBar.setProgress(currentPosition);

            // 总的播放时长
            int minute = duration / 1000 / 60;
            int second = duration / 1000 % 60;
            tvTotal.setText(minute + ":" + second);

            // 已经播放时长
            int currentMinute = currentPosition / 1000 / 60;
            int currentSecond = currentPosition / 1000 % 60;
            tvProgress.setText(currentMinute + ":" + currentSecond);
        }
    };

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected");
            // 当Service绑定上之后触发的方法
            musicContrll = (MusicService.MusicContrll) service;
            musicContrll.init(path);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_play);
        initView();
        initData();

        // 启动Service
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, connection , BIND_AUTO_CREATE);
    }

    private void initData() {
        Intent intent = getIntent();
        path = intent.getStringExtra("path");
        mp3List = (ArrayList<String>) intent.getSerializableExtra("mp3List");
        currentMusicIndex = mp3List.indexOf(path);
    }

    private void initView() {
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        tvProgress = (TextView) findViewById(R.id.tv_progress);
        tvTotal = (TextView) findViewById(R.id.tv_total);
        ivPrevious = (ImageView) findViewById(R.id.iv_previous);
        ivPlay = (ImageView) findViewById(R.id.iv_play);
        ivNext = (ImageView) findViewById(R.id.iv_next);

        ivPrevious.setOnClickListener(this);
        ivPlay.setOnClickListener(this);
        ivNext.setOnClickListener(this);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            // 滑动条拖动
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            // 开始滑动
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            // 停止滑动时候
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 得到当前停止的位置
                int progress = seekBar.getProgress();
                // 调用Service提供的seekTo方法改变音乐播放的位置
                musicContrll.seekTo(progress);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_previous:
                // 卫操作：对于非法的操作直接拦截，return后面的代码不需要执行
                if (currentMusicIndex == 0) {
                    Toast.makeText(this, "这已经是第一首歌曲了", Toast.LENGTH_LONG).show();
                    return;
                }
                currentMusicIndex--;
                musicContrll.init(mp3List.get(currentMusicIndex));
                ivPlay.setImageDrawable(getResources().getDrawable(R.drawable.playbar_play));
                break;
            case R.id.iv_play:
                if (musicContrll.isPlaying()) {
                    musicContrll.pause();
                    ivPlay.setImageDrawable(getResources().getDrawable(R.drawable.playbar_pause));
                } else {
                    musicContrll.play();
                    ivPlay.setImageDrawable(getResources().getDrawable(R.drawable.playbar_play));
                }
                break;
            case R.id.iv_next:
                // 卫操作：对于非法的操作直接拦截，return后面的代码不需要执行
                if (currentMusicIndex == mp3List.size() - 1) {
                    Toast.makeText(this, "这已经是最后一首歌曲了", Toast.LENGTH_LONG).show();
                    return;
                }
                currentMusicIndex++;
                musicContrll.init(mp3List.get(currentMusicIndex));
                ivPlay.setImageDrawable(getResources().getDrawable(R.drawable.playbar_play));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解绑Service
        musicContrll.pause();
        // 解绑服务
        unbindService(connection);
        Intent intent = new Intent(this, MusicService.class);
        stopService(intent);
    }
}